<template>
  <div>
    <div class="buttonBox">
      <el-button type="primary" @click="submit">同意微信授权</el-button>
    </div>
  </div>
</template>

<script>
  import { wxLogin } from "@/request/request.js";
  export default {
    data() {
      return {
        appID: "wx0321989f72146a62",
        loc_href: 'http://192.168.0.31:8080/',
        state : 'STATE'
      };
    },
    mounted() {
      this.handleWeixinCallback()
    },
    methods: {
      async  handleWeixinCallback() {
        const urlParams = new URLSearchParams(window.location.search);
        const code = urlParams.get('code');
        if (code) {
          // 发送 POST 请求到你的后端 API
          const res = await wxLogin({ code });
         if(res.code==200){
           localStorage.setItem('token',res.token)
           localStorage.setItem('userName',res.userName)
           // console.log(localStorage.getItem('token'),'134515')
           // console.log(res);
         }          // 处理登录成功后的逻辑

        } else {
          console.error('没有找到 code 参数');
        }
      },
      submit() {
        const appID = this.appID; // 替换为你的微信应用 ID
        const redirect_uri = encodeURIComponent(this.loc_href);
        const state = this.state; // 用于安全验证，可以是任意字符串
        const url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appID}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=${state}#wechat_redirect`;
        window.location.href = url;
        this.handleWeixinCallback()
      },
    }
  };
</script>

<style scoped>
  .buttonBox {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-top: 80px;
  }
</style>
